package com.crawler.harbour.task;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.crawler.harbour.dto.HYGShipmentDto;
import com.crawler.harbour.model.Notice;
import com.crawler.harbour.model.ShipmentHyg;
import com.crawler.harbour.model.ShipmentNew;
import com.crawler.harbour.service.INoticeService;
import com.crawler.harbour.service.IShipmentNewService;
import com.crawler.harbour.utils.AESUtil;
import com.crawler.harbour.utils.MapToBeanUtil;
import com.crawler.harbour.utils.RuoKuai;
import com.crawler.harbour.utils.StorageDay;
import com.crawler.harbour.utils.StringUtils;
import com.crawler.harbour.utils.UrlUtil;
import com.crawler.utils.BeanUtils;
import com.crawler.utils.RedisManager;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import net.dongliu.requests.Requests;
import net.dongliu.requests.Response;
import net.dongliu.requests.Session;

@Component
public class FZhygTask extends StorageDay{

	@Autowired
    IShipmentNewService shipmentNewService;

    @Autowired
    private INoticeService noticeService;

    //海盈码头
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void queryShipmentHyg(){
    	if(!RedisManager.lock("ship:queryShipmentHyg", 0)) {
    		return;
    	}
        HYGShipmentDto hygShipmentDto = new HYGShipmentDto();
        Session session = Requests.session();
//        String token ="";
        Response<String> login = session.get("http://www.hygw.com.cn:789/login.aspx?FromUrl=http%3a%2f%2fwww.hygw.com.cn%3a789%2findex.aspx").send().toTextResponse();
//        token = login.getCookie("HY_WEB_JsTicket").getValue();
        Map<String,Object> indexData = new HashMap<>();
        indexData.put("Action","Login");
        indexData.put("password",AESUtil.xhct("123"));
        indexData.put("username",AESUtil.xhct("guest"));
        Response<String> index = session.post(UrlUtil.LOGIN).body(indexData).send().toTextResponse();
        hygShipmentDto.setEncrpyCls(AESUtil.xhct("*"));
        hygShipmentDto.setView(AESUtil.xhct("VesselScheduleQuery"));
        JSONObject jsonObject = JSONUtil.parseObj(hygShipmentDto);

        Response<String> result = session.post(UrlUtil.HYGPU).body(jsonObject).send().toTextResponse();

        Map<String,Object> resultMap = JSON.parseObject(result.getBody());
        JSONArray rows = JSON.parseArray(resultMap.get("Rows").toString());
        Date date=new Date();
        List<String> IdList =new ArrayList<>();
        for (Object row:rows){
            Map<String,Object> rowMap = JSON.parseObject(row.toString());
            ShipmentHyg shipmentHyg = MapToBeanUtil.shipmentHyg(rowMap);
            ShipmentNew shipmentNew = new ShipmentNew();
            String voyage = shipmentHyg.getShipTime();   
            String JkHangci = Judging(voyage, "进口");
            String CKHangci = Judging(voyage, "出口");
            
            Notice notice = new Notice();
            notice.setPortNo("HYG");
            shipmentNew.setWharfName("海盈港");
            notice.setShipName(null);
            notice.setShipCnName(shipmentHyg.getShipName());
            notice.setJkShipTimer(StringUtils.nuller(JkHangci));
            notice.setCkShipTimer(StringUtils.nuller(CKHangci));
            notice.setJkSailingDate(StringUtils.nuller(shipmentHyg.getBerthingTime()));
            notice.setCkSailingDate(StringUtils.nuller(shipmentHyg.getUnberthingTime()));
            notice.setIntoDate(StringUtils.nuller(shipmentHyg.getEntryTime()));
            notice.setOffDate(StringUtils.nuller(shipmentHyg.getCutOffTime()));
            notice.setBerthDate(StringUtils.nuller(shipmentHyg.getBerthingTime()));
            notice.setLeaveDate(StringUtils.nuller(shipmentHyg.getUnberthingTime()));
            notice.setCutOffDate(StringUtils.nuller(shipmentHyg.getCutDanTime()));            
            notice.setStatus(0);
            notice.setCreateTime(date);
            if(StringUtils.isBlank(notice.getShipName())) {
            	notice.setShipName(notice.getShipCnName());
            }
            BeanUtils.copyProperties(notice,shipmentNew , "id","status","type","shipTimer","sailingDate");
            
            String hashStr = null;
            ShipmentNew oldTemp1 =null;
            ShipmentNew oldTemp2 =null;
            if(JkHangci!=null) {
            	shipmentNew.setType(1);
            	hashStr = RuoKuai.MD5("HYG"+shipmentHyg.getShipName()+JkHangci+"_1");
            	shipmentNew.setId(hashStr);
            	shipmentHyg.setId(hashStr);
            	shipmentNew.setShipTimer(JkHangci);
            	ShipmentNew temp = shipmentNewService.selectById(hashStr);
            	if (temp != null) {
            		oldTemp1= temp;
            	}
            	shipmentNew.setSailingDate(notice.getJkSailingDate());
            	shipmentNewService.insertOrUpdateAllColumn(shipmentNew);
            }
            
            if(CKHangci!=null) {
            	ShipmentNew shipmentNew2 = new ShipmentNew();
            	BeanUtils.copyProperties(shipmentNew,shipmentNew2);
            	shipmentNew2.setType(2);
            	shipmentNew2.setShipTimer(CKHangci);
            	hashStr = RuoKuai.MD5("HYG"+shipmentHyg.getShipName()+CKHangci+"_2");
            	shipmentNew2.setId(hashStr);
            	ShipmentNew temp = shipmentNewService.selectById(hashStr);
            	if (temp != null) {
            		oldTemp2= temp;
            	}
            	shipmentNew2.setSailingDate(notice.getCkSailingDate());
            	shipmentNewService.insertOrUpdateAllColumn(shipmentNew2);
            }
            
            boolean isOk = true;
		    if(oldTemp1!=null&&IdList.contains(oldTemp1.getId())||oldTemp2!=null&&IdList.contains(oldTemp2.getId())) {
		         isOk = false;
		    }
            if(isOk) {    
	                if(oldTemp1!=null&&!oldTemp1.getSailingDate().equals(StringUtils.nuller(shipmentHyg.getBerthingTime()))){
	                	if(StringUtils.nuller(oldTemp1.getSailingDate()).equals("")) {
	                		notice.setType(0);
	                	}else {
	                		notice.setType(4);
	                	}
	                    notice.setId(null);
	                    notice.setOrigValue(oldTemp1.getSailingDate());
	                    noticeService.insert(notice);
	                }
	                if(oldTemp2!=null&&!oldTemp2.getSailingDate().equals(StringUtils.nuller(shipmentHyg.getUnberthingTime()))){
	                	if(StringUtils.nuller(oldTemp2.getSailingDate()).equals("")) {
	                		notice.setType(0);
	                	}else {
	                		notice.setType(1);
	                	}
	                    notice.setId(null);
	                    notice.setOrigValue(oldTemp2.getSailingDate());
	                    noticeService.insert(notice);
	                }
	                if(oldTemp2!=null&&!oldTemp2.getIntoDate().equals(StringUtils.nuller(shipmentHyg.getEntryTime()))){
	                    notice.setType(3);
	                    notice.setId(null);
	                    notice.setOrigValue(oldTemp2.getIntoDate());
	                    noticeService.insert(notice);
	                }
	                if(oldTemp2!=null&&!oldTemp2.getOffDate().equals(StringUtils.nuller(shipmentHyg.getCutOffTime()))){
	                    notice.setType(2);
	                    notice.setId(null);
	                    notice.setOrigValue(oldTemp2.getOffDate());
	                    noticeService.insert(notice);
	                }
	                if(oldTemp1!=null) {
		            	  IdList.add(oldTemp1.getId());
		            }
		            if(oldTemp2!=null) {
		            	  IdList.add(oldTemp2.getId());
		            }
	         }
        }
    }
    
    public String Judging(String parme,String patten) {
        Pattern compile = Pattern.compile("([^\\)]+)\\("+patten+"\\)");
        Matcher matcher = compile.matcher(parme);
        while(matcher.find()) {
           return matcher.group(1);
          }
        return null;
  }

}
